package com.deng.wxmessagecallback.controller;

import cn.hutool.http.HttpUtil;
import com.deng.wxmessagecallback.config.apollo.ApolloConfig;
import com.deng.wxmessagecallback.pojo.request.MessageCallbackRequest;
import com.deng.wxmessagecallback.pojo.response.MessageCallbackResponse;
import com.deng.wxmessagecallback.qiyeweixin.aes.AesException;
import com.deng.wxmessagecallback.qiyeweixin.aes.WXBizMsgCrypt;
import com.deng.wxmessagecallback.service.TokenService;
import com.deng.wxmessagecallback.utils.CommonUtils;
import com.deng.wxmessagecallback.utils.message.DefaultTemplate;
import com.deng.wxmessagecallback.utils.message.WelcomeTemplate;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.cp.bean.external.WxCpWelcomeMsg;
import me.chanjar.weixin.cp.bean.external.msg.Link;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

/**
 * @author wbdengtt
 * @date 2021/1/11 15:57
 */
@RestController
@Slf4j
public class MessageCallbackController {

    @Autowired
    TokenService tokenService;

    @GetMapping("message-callback")
    public String messageCallback(@RequestParam(value = "msg_signature")String signature, @RequestParam("timestamp") String timestamp,
                                  @RequestParam("nonce") String nonce, @RequestParam(value = "echostr") String echoStr ) throws AesException {

        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(CommonUtils.sToken, CommonUtils.sEncodingAESKey, CommonUtils.sCorpID);

        String sEchoStr;
        try{
            sEchoStr = wxcpt.VerifyURL(signature,timestamp,nonce,echoStr);
            return sEchoStr;
        }catch (Exception exception) {
            log.error(exception.toString());
        }
        return "未能接收到数据";

    }

    /**
     * 这个目前是原样返回
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce 随机字符串
     * @param request 消息体
     * @return
     * @throws AesException
     */
    @PostMapping(value = "message-callback", consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public String messageCallback2(@RequestParam(value = "msg_signature")String signature, @RequestParam("timestamp") String timestamp,
                                                    @RequestParam("nonce") String nonce, @RequestBody MessageCallbackRequest request) throws AesException {
        MessageCallbackResponse response = new MessageCallbackResponse();
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(CommonUtils.sToken, CommonUtils.sEncodingAESKey, CommonUtils.sCorpID);
        try {
            // 揭秘的内容
            String sEchoStr = wxcpt.VerifyURL(signature,timestamp,nonce,request.getEncrypt());
            log.info("接收的内容是{}",sEchoStr);
            //response.setEncrypt(request.getEncrypt());
            WxCpXmlMessage wxCpXmlMessage = XStreamTransformer.fromXml(WxCpXmlMessage.class,sEchoStr);
            // 向自建应用发送欢迎 怎么处理
            if (wxCpXmlMessage.getMsgType().equals(WxConsts.XmlMsgType.TEXT) && wxCpXmlMessage.getContent().contains("欢迎")) {
                return WelcomeTemplate.getNewsMessage(wxCpXmlMessage.getToUserName(),wxCpXmlMessage.getFromUserName());
            }
            // 添加企业客户事件 耦合性实在太高了 更好的做法是通过消息队列将内容推送出去。由另外的服务发送欢迎语
            if (wxCpXmlMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT) && "change_external_contact".equals(wxCpXmlMessage.getEvent()) && "add_external_contact".equals(wxCpXmlMessage.getChangeType())) {
                // 取出welcomeCode
                String welcomeCode = wxCpXmlMessage.getWelcomeCode();
                // 获取token
                String token = tokenService.getExternalContactToken();

                // 发送消息
                // 1. 构造消息链接  url+token
                String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token=" + token;
                // 2. 构造发送的内容
                Link link = new Link();
                link.setDesc(ApolloConfig.getBaseValue("WxCpWelcomeMessage-description"));
                link.setPicUrl(ApolloConfig.getBaseValue("WxCpWelcomeMessage-picUrl"));
                link.setTitle(ApolloConfig.getBaseValue("WxCpWelcomeMessage-title"));
                link.setUrl(ApolloConfig.getBaseValue("WxCpWelcomeMessage-url"));
                WxCpWelcomeMsg msg = WxCpWelcomeMsg.builder().welcomeCode(welcomeCode).link(link).build();
                String jsonBody = msg.toJson();
                // 3. 发送消息
                HttpUtil.post(url,jsonBody);
                // 这里其实不需要我不需要返回什么东西。让后面默认返回吧
            }
            return DefaultTemplate.getTextMessage(wxCpXmlMessage.getFromUserName(),wxCpXmlMessage.getToUserName());
        }catch (Exception e) {
            log.error(e.toString());
            return null;
        }

    }
}
